<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class BaseModel extends Model
{
    public $model;

    public function __construct($model)
    {
        parent::__construct();
        $this->model = new $model;
    }

    public function getInstance(){
        return $this->model;
    }
    /**
     * 更复杂的结构 建议自己用 MODEL 实例重新编写  参数传递太多太丑
     * @param array $where  ['id' => 1]
     * @param array $orderBy ['id'=> 'desc','sort' => 'asc']
     * @param array $select  ['id’,'name']
     * @return Collection
     */
    public function getModelLists(array $where = [],array $select = ['*'],array $orderBy = []):Collection
    {
        $model = $this->model;
        $model = $model->where($where)->select($select);
        if(!empty($orderBy)){
            foreach ($orderBy as $key => $item){
                $model->orderBy($key,$item);
            }
        }
        return $model->get();
    }

    /**
     * 获取详情  注意条件不存在会返回NULL
     * @param array $where
     * @return mixed
     */
    public function getModelDetail(array $where = [])
    {
        return $this->model->where($where)->first();
    }

    /**
     * 查询模型数据是否存在
     * @param array $where
     * @return Collection
     */
    public function getModelExists(array $where)
    {
        return $this->model->where(where)->exists();
    }


    /**
     * 查询模型数据是否存在
     * @param array $where
     * @return Collection
     */
    public function getModelCount(array $where)
    {
        return $this->model->where(where)->count();
    }


    /**
     * 创建数据
     * @param array $data
     * @return Collection
     */
    public function createModel(array $data)
    {
        return $this->model->create($data);
    }

    /**
     * 更新数据
     * @param array $where
     * @param array $update
     * @return Collection
     */
    public function updateModel(array $where, array $update)
    {
        return $this->model->where($where)->update($update);
    }

    /**
     * 删除数据
     * @param array $where
     */
    public function deleteModel(array $where){
        return $this->model->where($where)->delete();
    }
}
